package com.imooc.controller;

import com.imooc.aspect.HttpAspect;
import com.imooc.domain.Girl;
import com.imooc.respository.GirlRespontery;
import com.imooc.service.GirlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by Macoco on 2017-05-07.
 */
@RestController
public class GirlController {

    private final static Logger logger = LoggerFactory.getLogger(GirlController.class);

    @Autowired
    private GirlRespontery girlRespontery;

    @RequestMapping(value = "/girls")
    public List<Girl> girlList() {
        logger.info("girlList() run33333333333");
        //        System.out.println("2222222");
        return girlRespontery.findAll();
    }

    /**
     * 添加一个女生
     *
     * @param girl
     * @return
     */
// public Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) {
    @PostMapping(value = "/girls")
    public Girl girAdd(@Valid Girl girl, BindingResult bindingResult) {
        //不加此判断，逻辑方法依旧执行
//        此处与教程有误差，需要使用put方法提交方能实现效果
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        girl.setCupSize(girl.getCupSize());
        girl.setAge(girl.getAge());
        return girlRespontery.save(girl);
    }

    /**
     * 查询一个女生
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/girls/{id}")
    public Girl girlFindOne(@PathVariable("id") Integer id) {
        return girlRespontery.findOne(id);
    }

    /**
     * 更新,注意路径中的变量是pathvariable
     *
     * @param id
     * @param cupSize
     * @param age
     * @return
     */
    @PutMapping(value = "/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id,
                           @RequestParam("cupSize") String cupSize,
                           @RequestParam("age") Integer age) {
        Girl girl = new Girl();
        girl.setAge(age);
        girl.setCupSize(cupSize);
        girl.setId(id);
        return girlRespontery.save(girl);
    }

    @DeleteMapping(value = "/girls/{id}")
    public void girlDelete(@PathVariable("id") Integer id) {
        girlRespontery.delete(id);
    }

    @Autowired
    private GirlService girlService;

    /**
     * 通过年龄更新女生
     *
     * @param age
     * @return
     */
    @GetMapping(value = "/girls/age/{age}")
    public List<Girl> girlsListByAge(@PathVariable("age") Integer age) {
        return girlRespontery.findByAge(age);
    }

    @GetMapping(value = "/girls/two")
    public void girlTwo() {
        girlService.insertTwo();
    }
}





